package com.security.springcloud.uaa.service;

import com.security.springcloud.uaa.dao.UserDao;
import com.security.springcloud.uaa.model.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yingyuwei
 * @version 1.0.0
 * @description 自定义用户获取服务类，用户spring security -> provider 中获取用户进行检验
 * @createTime 2021年02月27日 19:06:00
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO userDTO = userDao.queryByUsername(username);
        if (userDTO == null) {
            return null;
        }
        List<String> authorities = userDao.queryPermissionByUserId(userDTO.getId());
        //可通过数据查询获取
        UserDetails userDetails = User
                .withUsername(userDTO.getUsername())
                .password(userDTO.getPassword())
                .authorities(authorities.toArray(new String[authorities.size()])).build();
        return userDetails;
    }

}
